package com.central.scheduler.plugin.task.util;

import com.central.common.constant.CommonConstant;
import lombok.extern.slf4j.Slf4j;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hdfs.HdfsConfiguration;

import java.io.IOException;

/**
 * @author Tindy
 * @date 2022/1/16
 * @describe 用户操作hadoop 工具，
 */
@Slf4j
public class UserHadoopUtils {
    private Configuration configuration;
    private FileSystem fs;
    private String user;
    private String keytabPath;
    private String krb5ConfPath;
    private String defaultFS;
    public UserHadoopUtils(String user, String keytabPath, String krb5ConfPath, String defaultFS){
        this.user=user;
        this.keytabPath=keytabPath;
        this.krb5ConfPath=krb5ConfPath;
        this.defaultFS=defaultFS;
        init();
    }

    /**
     * init hadoop configuration
     */
    private void init() {
        try {
            configuration = new HdfsConfiguration();
            configuration.set("fs.defaultFS",this.defaultFS);
            String loginUser= user;
            synchronized (CommonConstant.KRB5CONF_LOCK){
                CommonUtils.loadKerberosConf(this.krb5ConfPath,
                        loginUser,
                        keytabPath, configuration);
                fs = FileSystem.get(configuration);
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }

    public boolean exists(String udfJarHdfsPath) throws IOException {
        return fs.exists(new Path(udfJarHdfsPath));
    }
    /**
     * the src file is on the local disk.  Add it to FS at
     * the given dst name.
     *
     * @param srcFile local file
     * @param dstHdfsPath destination hdfs path
     * @param deleteSource whether to delete the src
     * @param overwrite whether to overwrite an existing file
     * @return if success or not
     * @throws IOException errors
     */
    public boolean copyLocalToHdfs(String srcFile, String dstHdfsPath, boolean deleteSource, boolean overwrite) throws IOException {
        Path srcPath = new Path(srcFile);
        Path dstPath = new Path(dstHdfsPath);

        fs.copyFromLocalFile(deleteSource, overwrite, srcPath, dstPath);

        return true;
    }
}
